package cn.wen.rpc.server;

import cn.wen.rpc.annotation.WenService;
import cn.wen.rpc.config.WenRpcConfig;
import cn.wen.rpc.exception.WenRpcException;
import cn.wen.rpc.factory.SingletonFactory;
import cn.wen.rpc.netty.NettyServer;
import cn.wen.rpc.register.nacos.NacosTemplate;
import com.alibaba.nacos.api.naming.pojo.Instance;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class WenServiceProvider {

    private WenRpcConfig wenRpcConfig;

    private final Map<String, Object> serviceMap;
    private NacosTemplate nacosTemplate;
    
    public WenServiceProvider(){
        serviceMap = new ConcurrentHashMap<>();
        nacosTemplate = SingletonFactory.getInstance(NacosTemplate.class);
    }

    public void publishService(WenService wenService, Object service) {
        registerService(wenService,service);
        // 启动nettyServer 这个方法会调用多次，服务只能启动一次
        NettyServer nettyServer = SingletonFactory.getInstance(NettyServer.class);
        nettyServer.setWenServiceProvider(this);
        if (!nettyServer.isRunning()){
            nettyServer.run();
        }
    }

    private void registerService(WenService wenService, Object service) {
        String version = wenService.version();
        String interfaceName = service.getClass().getInterfaces()[0].getCanonicalName();
        log.info("发布了服务:{}",interfaceName);
        serviceMap.put(interfaceName + version,service);
        // 同步注册到Nacos中
        // group 只有在同一个组内 调用关系才能成立，不同的组之间是隔离的
        if (wenRpcConfig == null){
            throw new WenRpcException("必须开启EnableRPC");
        }
        try {
            Instance instance = new Instance();
            instance.setIp(InetAddress.getLocalHost().getHostAddress());
            instance.setPort(wenRpcConfig.getProviderPort());
            instance.setClusterName("wen-rpc");
            instance.setServiceName(interfaceName + version);
            nacosTemplate.registerServer(wenRpcConfig.getNacosGroup(), instance);
        }catch (Exception e){
            log.error("nacos注册失败:",e);
        }

    }

    public Object getService(String serviceName){
        return serviceMap.get(serviceName);
    }

    public WenRpcConfig getWenRpcConfig() {
        return wenRpcConfig;
    }

    public void setWenRpcConfig(WenRpcConfig wenRpcConfig) {
        this.wenRpcConfig = wenRpcConfig;
    }
}
